package com.kstech.mp3604.data.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.kstech.mp3604.base.Global
import com.kstech.mp3604.bean.TaskData

/**
 * author: blankii
 * created on: 2025/4/23 13:31
 * description:
 * todo 不再以task为一个单位，以一个堆信息为基础单位
 */
@Dao
interface TaskDataDao {

    // 查询
    @Query("SELECT * FROM taskData ORDER BY timestamp DESC LIMIT ${Global.OVERTIME_RETAIN_COUNT}")
    fun queryAllTask(): MutableList<TaskData>

    //查询数据总条数
    @Query("SELECT count(*) FROM taskData")
    fun queryAllTaskCountNum(): Int
    //根据姓名参数查询
    @Query("SELECT * FROM taskData WHERE (taskId = :taskId OR :taskId ='') AND (batchNo = :batchNo OR :batchNo ='') AND (DATE(timestamp) = :date OR :date ='')")
    fun queryFindTaskData(taskId: String, batchNo: String, date: String): MutableList<TaskData>

    // 添加单条数据
    @Insert
    fun addTaskData(taskData: TaskData)

    // 添加批量数据
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun addBatchTaskData(list: List<TaskData>)

    // 更新某一个数据
    @Update
    fun updateTaskData(vararg taskData: TaskData)

    //删除某一个数据
    @Delete
    fun deleteTaskData(taskData: TaskData)

    //按条件删除
    @Query("DELETE FROM taskData WHERE taskId = :taskId")
    fun deleteTaskDataById(taskId: String)

    @Query("DELETE FROM taskData WHERE timestamp<:date")
    fun deleteOldTaskData(date:Long)

    //delete 不能直接使用order
//    @Query("DELETE FROM taskData ORDER BY timestamp ASC LIMIT ${Global.OVERTIME_MAX_COUNT - Global.OVERTIME_RETAIN_COUNT}")
    @Query("DELETE FROM taskData WHERE taskId IN (SELECT taskId FROM  taskData ORDER BY timestamp ASC LIMIT ${Global.OVERTIME_MAX_COUNT - Global.OVERTIME_RETAIN_COUNT})")
    fun deleteOverTimeData()

    fun checkData() {
        //检查任务表当前存储的数据条数是否达到溢出值
        val currentCount = queryAllTaskCountNum()//当前数据条数
        if (currentCount >= Global.OVERTIME_MAX_COUNT) {
            //排好序之后保留固定数据的数据其他全部删除
            deleteOverTimeData()
        }
    }
}